package am.sample.route;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.Logger;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.Assert;

import am.api.AMConnection;
import am.api.AMConnectionFactory;
import am.api.model.AMString;

public class DisplayUsers extends RouteBuilder {

	private Logger log = Logger.getLogger(DisplayUsers.class);
	private PlatformTransactionManager transactionManager;
	private AMConnectionFactory amConnectionFactory;

	public void init() {
		Assert.notNull(transactionManager, "transactionManager is required.");
		Assert.notNull(amConnectionFactory, "amConnectionFactory is required.");
	}

	protected void clearLastError(AMConnection connection) {
		if (connection != null && 0 != connection.lastError()) {
			connection.clearLastError();
		}
	}

	protected void closeConnection(AMConnection connection) {
		if (connection != null) {
			connection.close();
		}
	}

	public PlatformTransactionManager getTransactionManager() {
		return transactionManager;
	}

	public void setTransactionManager(
			PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	@Override
	public void configure() throws Exception {

		// this doesn't do much, just performs a query on AM every 60 seconds

		from("timer:amSample?period=60000").transacted("PROPAGATION_REQUIRED")
				.process(new Processor() {

					public void process(final Exchange exchange)
							throws Exception {

						AMConnection connection = null;

						int qryHandle = 0;

						try {

							connection = amConnectionFactory.getConnection();

							qryHandle = connection.queryCreate();

							Assert.isTrue(qryHandle > 0,
									"Could not create query handle");

							Assert.isTrue(
									connection
											.queryExec(qryHandle,
													"SELECT UserLogin FROM amEmplDept WHERE UserLogin <> ''") == 0,
									"Could not execute query");

							while (connection.queryNext(qryHandle) == 0) {

								AMString amUserLogin = AMString.create(255);

								Assert.isTrue(connection.getFieldStrValue(
										qryHandle, 0, amUserLogin) == 0,
										"Could not retrieve value");

								log.debug(String.format("UserLogin = %s",
										amUserLogin.toString()));
							}

						} finally {
							if (qryHandle > 0) {
								Assert.isTrue(
										connection.releaseHandle(qryHandle) == 0,
										"Could not release query handle");
							}
							closeConnection(connection);
						}

					}

				});

	}

	public AMConnectionFactory getAmConnectionFactory() {
		return amConnectionFactory;
	}

	public void setAmConnectionFactory(AMConnectionFactory amConnectionFactory) {
		this.amConnectionFactory = amConnectionFactory;
	}
}
